package com.fanyouzhao.ehome.web.servlet;

import com.alibaba.fastjson.JSON;
import com.fanyouzhao.ehome.entity.Cp;
import com.fanyouzhao.ehome.entity.User;
import com.fanyouzhao.ehome.service.UserService;
import com.fanyouzhao.ehome.service.impl.UserServiceImpl;
import com.fanyouzhao.ehome.util.JsonResult;
import com.fanyouzhao.ehome.util.ResponseUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @Author: fanyouzhao
 * @Date: 14:17 2021/4/25
 */
@WebServlet(name = "UserServlet", value = "/user")
public class UserServlet extends HttpServlet {

    private final UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //中文处理
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        ((HttpServletResponse)response).setHeader("content-Type","text/html;charset=UTF-8");

        JsonResult jsonResult = new JsonResult();
        jsonResult.setData(null);

        //获取操作的类型 method
        String method = request.getHeader("method");
        switch (method) {
            case "login": {
                String phone = request.getParameter("phone");
                try {
                    User loginUser = login(phone);
                    if (loginUser!=null){
                        HttpSession session = request.getSession();
                        session.setAttribute("phone", phone);
                        jsonResult.setCode("0");
                        jsonResult.setMsg("登录成功！");
                        jsonResult.setData(loginUser);
                    }else{
                        jsonResult.setCode("1");
                        jsonResult.setMsg("该手机号未注册！");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }
            case "reg": {
                String formData = request.getParameter("formData");
                String code = request.getParameter("code");
                System.out.println("formData = " + formData);
                System.out.println("code = " + code);

                User user = JSON.parseObject(formData, User.class);
                user.setRegTime(new Date());
                System.out.println("user = " + user);
                try {
                    Object codeSession = request.getSession().getAttribute("code");
                    System.out.println("codeSession = " + codeSession);
                    if (codeSession!=null){
                        if (codeSession.toString().equals(code)){
                            User register = register(user);
                            if (register != null) {
                                jsonResult.setCode("0");
                                jsonResult.setMsg("注册成功！");
                                jsonResult.setData(register);
                            } else {
                                jsonResult.setCode("1");
                                jsonResult.setMsg("注册失败！");
                            }
                        }else{
                            jsonResult.setCode("1");
                            jsonResult.setMsg("验证码错误！");
                        }
                    }else{
                        jsonResult.setCode("1");
                        jsonResult.setMsg("验证码错误！");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }
            case "selectByPage": {
                Integer page = Integer.parseInt(request.getParameter("page"));
                Integer limit = Integer.parseInt(request.getParameter("limit"));
                try {
                    List<User> users = selectByPage(page, limit);
                    if (users != null) {
                        jsonResult.setCode("0");
                        jsonResult.setMsg("查询成功");
                        jsonResult.setData(users);
                        jsonResult.setValue("count",getCount());
                    } else {
                        jsonResult.setCode("1");
                        jsonResult.setMsg("查询失败！");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }
            case "myInf": {
                String phone = request.getParameter("phone");
                try {
                    User user = selectByPhone(phone);
                    if (user != null) {
                        jsonResult = new JsonResult("0","查询成功",user);
                    } else {
                        jsonResult = new JsonResult("1","查询失败");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }
            case "export": {
                try {
                    List<User> users = selectAll();
                    String s = JSON.toJSONString(users);
                    request.setAttribute("dataJSONString",s);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }
            case "getCpn": {
                Integer cpId = Integer.parseInt(request.getParameter("cpId"));
                String phone = request.getParameter("phone");
                try {
                    if (getCpn(cpId,phone)){
                        jsonResult = new JsonResult("1","申请成功");
                    }else{
                        jsonResult = new JsonResult("0","申请失败");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }
            case "search": {
                Integer page = Integer.parseInt(request.getParameter("page"));
                Integer limit = Integer.parseInt(request.getParameter("limit"));
                String searchString = request.getParameter("searchString");
                try {
                    List<User> searchUsers = search(searchString, page, limit);
                    if (searchUsers != null) {
                        jsonResult = new JsonResult("0","查询成功",searchUsers);
                        jsonResult.setValue("count",getCountSearch(searchString));
                    } else {
                        jsonResult = new JsonResult("1","查询失败！");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }
            case "getCpnListForWeb": {
                String phone = request.getParameter("phone");
                HashMap<String, Object> getCpnListForWeb = new HashMap<>();
                try {
                    List<Cp> userNotGetCpnList = selectNotGetCpsByPhone(phone);
                    List<Cp> userGetCpnList = selectGetCpsByPhone(phone);
                    List<Cp> overExpire = selectOverExpireCpsByPhone(phone);
                    getCpnListForWeb.put("userNotGetCpnList",userNotGetCpnList);
                    getCpnListForWeb.put("userGetCpnList",userGetCpnList);
                    getCpnListForWeb.put("overExpire",overExpire);
                    jsonResult = new JsonResult("0","查询成功",getCpnListForWeb);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }
            default:
                break;
        }
        ResponseUtil.send(response, JSON.toJSONString(jsonResult.getValues()));
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    public User login(String phone) throws Exception {
        return userService.login(phone);
    }

    public User register(User user) throws Exception {
        return userService.register(user);
    }

    public List<User> selectByPage(Integer page,Integer size) throws Exception{
       return userService.selectByPage(page, size);
    }
    public User selectByPhone(String phone) throws Exception{
        return userService.selectByPhone(phone);
    }
    public Integer getCount() throws Exception{
        return userService.getCount();
    }
    public Integer getCountSearch(String searchString) throws Exception{
        return userService.getCountSearch(searchString);
    }

    public List<User> selectAll() throws Exception{
        return userService.selectAll();
    }
    public List<User> search(String searchString, Integer page, Integer size) throws Exception{
        return userService.searchByPhoneorName(searchString,page,size);
    }

    public List<Cp> selectNotGetCpsByPhone(String phone) throws Exception{
        return userService.selectNotGetCpsByPhone(phone);
    }
    public List<Cp> selectGetCpsByPhone(String phone) throws Exception{
        return userService.selectGetCpsByPhone(phone);
    }
    public List<Cp> selectOverExpireCpsByPhone(String phone) throws Exception{
        return userService.selectOverExpireCpsByPhone(phone);
    }
    public Boolean getCpn(Integer cpId,String phone) throws Exception{
        return userService.getCpn(cpId, phone);
    }



}
